package cn.ztydata.teachingsystem.heaven.dao;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.heaven.common.WebContext;
import cn.ztydata.teachingsystem.heaven.entity.Daily;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * DailyDao
 *
 * @author lyj
 * @since 2015/5/6
 */
@Repository
public class DailyDao extends BaseDao {
    @Autowired
    private WebContext webContext;

    //<editor-fold desc="新增">
    /**
     * 新增教学日志
     * @param daily
     * @author lyj
     * @since 2015-5-6
     */
    public int addDaily(final Daily daily) {
        StringBuilder sql = new StringBuilder("INSERT INTO t_daily VALUES (NULL,:title,:contentText,:contentHtml,:creatorId,NOW(),:groupId,:open)");

        MapSqlParameterSource param = new MapSqlParameterSource()
                .addValue("title", daily.getTitle())
                .addValue("contentText", daily.getContentText())
                .addValue("contentHtml", daily.getContentHtml())
                .addValue("creatorId", webContext.getUserId())
                .addValue("groupId", daily.getGroupId())
                .addValue("open", daily.getOpen());

        log.debug("新增教学日志");
        return namedParameterJdbcTemplate.update(sql.toString(), param);
    }
    //</editor-fold>

    //<editor-fold desc="删除">
    /**
     * 删除日志
     *
     * @param id 日志ID
     * @return int
     * @author lyj
     * @since 2015-5-6
     */
    public int deleteById(final long id) {
        StringBuilder sql = new StringBuilder("DELETE FROM t_daily WHERE id = :id");

        log.debug("删除日志");
        return namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource().addValue("id", id));
    }
    //</editor-fold>

    //<editor-fold desc="编辑">
    /**
     * 编辑日志(只能自己编辑自己的)
     *
     * @param daily
     * @return int
     * @author lyj
     * @since 2015-5-6
     */
    public int updateDaily(final Daily daily) {
        StringBuilder sql = new StringBuilder("UPDATE t_daily SET sTitle = :title, sContentText = :contentText, sContentHtml = :contentHtml, tiOpen = :open WHERE id = :id AND iCreatorId = :creatorId");

        MapSqlParameterSource param = new MapSqlParameterSource()
                .addValue("title", daily.getTitle())
                .addValue("contentText", daily.getContentText())
                .addValue("contentHtml", daily.getContentHtml())
                .addValue("open", daily.getOpen())
                .addValue("id", daily.getId())
                .addValue("creatorId", webContext.getUserId());

        log.debug("编辑日志(只能自己编辑自己的)");
        return namedParameterJdbcTemplate.update(sql.toString(), param);
    }


    /**
     * 是否公开(只能自己编辑自己的)
     *
     * @param id 日志ID
     * @param open 是否公开
     * @return int
     * @author lyj
     * @since 2015-5-6
     */
    public int updateOpenById(final long id,final int open) {
        StringBuilder sql = new StringBuilder("UPDATE t_daily SET  tiOpen = :open WHERE id = :id AND iCreatorId = :creatorId");

        log.debug("是否公开(只能自己编辑自己的)");
        return namedParameterJdbcTemplate.update(sql.toString(), new MapSqlParameterSource()
                .addValue("id", id)
                .addValue("open", open)
                .addValue("creatorId", webContext.getUserId()));
    }
    //</editor-fold>

    //<editor-fold desc="查询">
    /**
     * 教学日志列表
     *
     * @param groupId  群组ID
     * @param pageNum  当前页码
     * @param pageSize 每页条数
     * @param tag      标记 0全部 1我的
     * @return Page<Daily>
     * @author lyj
     * @since 2015-5-6
     */
    public Page<Daily> getAllDailies(final long groupId, final int pageNum, final int pageSize, final int tag) {
        StringBuilder sql = new StringBuilder("SELECT d.id,d.sTitle,d.sContentText,d.iCreatorId,d.dtCreate,d.tiOpen,te.sName,te.sPicture FROM t_daily d JOIN t_teacher te ON d.iCreatorId = te.id");
        StringBuilder sqlCount = new StringBuilder("SELECT COUNT(d.id) FROM t_daily d JOIN t_teacher te ON d.iCreatorId = te.id");
        StringBuilder where = new StringBuilder(" WHERE 1 = 1");

        MapSqlParameterSource param = new MapSqlParameterSource();

        //过滤群组ID
        if (groupId > 0) {
            log.debug("过滤群组IDgroupId > 0");

            where.append(" AND d.iGroupId = :groupId");
            param.addValue("groupId", groupId);
        }

        //过滤创建人
        if (tag == 1) {
            log.debug("过滤创建人tag == 1");

            where.append(" AND d.iCreatorId = :creatorId");
            param.addValue("creatorId", webContext.getUserId());
        } else {
            where.append(" AND d.tiOpen = 1");
        }


        //获取查询总条数
        int total = namedParameterJdbcTemplate.queryForObject(sqlCount.append(where).toString(), param, Integer.class);

        //获取总条数
        if (total == 0) {
            log.debug("获取总条数total == 0");

            return new Page<>();
        }

        //排序
        where.append(" ORDER BY d.dtCreate DESC");

        //追加limit限制
        where.append(getLimitStr(pageNum, pageSize));

        List<Daily> dailyList = namedParameterJdbcTemplate.query(sql.append(where).toString(), param, new RowMapper<Daily>() {
            @Override
            public Daily mapRow(ResultSet resultSet, int i) throws SQLException {
                Daily daily = new Daily();

                daily.setId(resultSet.getLong("id"));
                daily.setTitle(resultSet.getString("sTitle"));
                daily.setContentText(resultSet.getString("sContentText"));
                daily.setCreatorId(resultSet.getLong("iCreatorId"));
                daily.setCreate(resultSet.getTimestamp("dtCreate"));
                daily.setOpen(resultSet.getInt("tiOpen"));
                daily.setCreatorName(resultSet.getString("sName"));
                daily.setCreatorPhoto(resultSet.getString("sPicture"));

                return daily;
            }
        });

        log.debug("教学日志列表");
        return new Page<>(total, pageSize, pageNum, dailyList);
    }


    /**
     * 跟据ID获取日志明细
     *
     * @param id 日志ID
     * @return Daily
     * @author lyj
     * @since 2015-5-6
     */
    public Daily getDetailById(final long id) {
        StringBuilder sql = new StringBuilder("SELECT id,sContentHtml,sContentText,tiOpen,sTitle,iCreatorId,iGroupId FROM t_daily WHERE id = :id");

        try {
            log.debug("跟据ID获取日志明细");
            return namedParameterJdbcTemplate.queryForObject(sql.toString(), new MapSqlParameterSource().addValue("id", id), new RowMapper<Daily>() {
                @Override
                public Daily mapRow(ResultSet resultSet, int i) throws SQLException {
                    Daily daily = new Daily();

                    daily.setId(resultSet.getLong("id"));
                    daily.setTitle(resultSet.getString("sTitle"));
                    daily.setContentHtml(resultSet.getString("sContentHtml"));
                    daily.setContentText(resultSet.getString("sContentText"));
                    daily.setOpen(resultSet.getInt("tiOpen"));
                    daily.setCreatorId(resultSet.getLong("iCreatorId"));
                    daily.setGroupId(resultSet.getLong("iGroupId"));

                    return daily;
                }
            });
        } catch (EmptyResultDataAccessException ex) {
            log.debug("获取日志明细失败");

            log.warn("获取日志明细失败：id->{}", id);
            return null;
        }
    }
    //</editor-fold>

}
